import 'bytemd/dist/index.css'
// 编辑 / 视图
import {Editor, Viewer} from '@bytemd/react';
import gfm from '@bytemd/plugin-gfm';
import highlight from '@bytemd/plugin-highlight'
import mediumZoom from "@bytemd/plugin-medium-zoom";
import gemoji from "@bytemd/plugin-gemoji";
// 引入中文包
import zhHans from "bytemd/lib/locales/zh_Hans.json";

// 引入基础css
import 'bytemd/dist/index.min.css';

//引入github编辑器样式
import 'github-markdown-css/github-markdown.css'

import '@/css/ByteMd.less'

// 引入高亮css
import "highlight.js/styles/vs.css";
import 'highlight.js/styles/atom-one-light.css'

import * as React from "react";

import {Input,Button,message,Modal,Select,Upload,Form} from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import type { UploadProps } from 'antd';
import {envApi} from "../../../public/api";

import {axiosRequest} from "@/service";

import {withRouter} from "@/hooks/withRouter";
import { Link } from 'react-router-dom';

const { TextArea } = Input;

const plugins = [gfm(), gemoji(), highlight(), mediumZoom()]

type StateType = {
    value: string
    title: string
    isModalOpen:boolean
    classifyOne:string
    classifyTwo:string
    abstract:string
    coverPic:string
}

class ByteMd extends React.Component<any, StateType> {
    constructor(props: any) {
        super(props);
        this.state = {
            value: '',
            title:'',
            isModalOpen: false,
            classifyOne:'001',
            classifyTwo:'002',
            abstract:'',
            coverPic:'',
        }
    }

    uploadImg(file: File[]): Promise<any> {
        return new Promise((resolve, reject) => {

            const formData = new FormData();
            formData.append("file", file[0])
            const config = {
                url: 'upload',
                method: 'post',
                data:formData
            }

            axiosRequest(config).then((res:any) => {
                resolve([{ title:'',url:res.url}])
            }).catch((err: any) => {
                reject('')
                console.error('this is a error', err)
            })
        })
    }

    setMyState = (obj:object) => {
        this.setState(Object.assign({}, this.state, obj))
    }

    submitArticle = () => {
        const config = {
            url: 'submitArticle',
            method: 'post',
            data:{
                title:this.state.title,
                content:this.state.value,
                abstract:this.state.abstract,
                coverPic:this.state.coverPic,
                classifyOne:this.state.classifyOne,
                classifyTwo:this.state.classifyTwo
            }
        }

        axiosRequest(config).then((res:any) => {
            if(res && res.code && res.code == 200){
                message.success('发布成功！')
                this.setMyState({isModalOpen: false})
            } else {
                message.error('发布失败！')
            }

        }).catch((err:any) => {
            message.error('发布失败！')
            console.error('this is a error', err)
        })
    }

    clickPublishArticle = () => {
        this.setMyState({isModalOpen: true})
    }

    option: UploadProps = {
        name: 'file',
        action: `${envApi.baseUrl}upload`,
        accept: "image/jpg, image/png",
        customRequest:(params:any) => {
            const { file, onSuccess, onError } = params;
            const formData = new FormData();
            formData.append("file", file)
            const config = {
                url: 'upload',
                method: 'post',
                data:formData
            }

            axiosRequest(config).then((res:any) => {
                this.setMyState({coverPic: res.url})
                onSuccess(res)
            }).catch((err:any) => {
                onError(err)
                console.error('this is a error', err)
            })

        },
        onChange:(info:any) => {
            if (info.file.status === 'done') {
                message.success(`${info.file.name} file uploaded successfully`);
            } else if (info.file.status === 'error') {
                message.error(`${info.file.name} file upload failed.`);
            }
        },
    };



    dialogJsx = () => {
        const bigClass = [
            { value: '001', label: '首页' },
            { value: '002', label: '原创' },
            { value: '003', label: '转载' },
            { value: '004', label: '资讯' },
            { value: '005', label: '书架' },
            { value: '006', label: '足迹' },
            { value: '007', label: '工具箱' }
            ]

        const smallClass = [
            { value: '002', label: '前端' },
            { value: '003', label: '后端' },
            { value: '004', label: '算法' },
            { value: '005', label: '架构' },
            { value: '006', label: '面试' },
            { value: '007', label: '阅读' },
            { value: '008', label: '笔记' }
            ]
        return (
            <Modal title="发文" open={this.state.isModalOpen} onOk={this.submitArticle} onCancel={() => this.setMyState({isModalOpen: false})}>
                <Form name="basic"
                      initialValues={{remember: true}}
                      autoComplete="off"
                      className="ruleForm"
                >
                    <Form.Item name="userName" rules={[{required: true, message: 'Choose Please!'}]}>

                        大分类：<Select
                            defaultValue="001"
                            onSelect={(val:any) => this.setMyState({classifyOne: val})}
                            style={{ width: 120 }}
                            options={bigClass}
                        />

                        <span style={{marginLeft: '20px'}}>
                            二级分类：<Select
                            defaultValue="002"
                            onSelect={(val:any) => this.setMyState({classifyTwo: val})}
                            style={{ width: 120 }}
                            options={smallClass}
                        />
                        </span>

                    </Form.Item>
                    <Form.Item>
                        <Upload {...this.option}>
                            <Button icon={<UploadOutlined />}>点击上传头图</Button>
                        </Upload>

                    </Form.Item>

                    <Form.Item rules={[{required: true, message: 'Choose Please!'}]}>
                        <TextArea rows={4} placeholder="请输入文章摘要" onChange={(val:any) => {this.setMyState({abstract: val.target.value})}} maxLength={200} />
                    </Form.Item>
                </Form>
            </Modal>
        )
    }

    render() {
        return (
            <div className="editor">
                <header className="title-header">
                    <Input placeholder="请输入文章标题" onChange={(val:any) => {this.setMyState({title: val.target.value})}} className="title-input"/>

                    <Link to='/'>
                        <Button className="flex-mar" >回首页</Button>
                    </Link>
                    <Button className="flex-mar" onClick={this.clickPublishArticle}>发文章</Button>
                    <img className="flex-mar" src={require('@/images/demo.jpg')} alt="头像"/>
                </header>

                <Editor
                    // 语言
                    locale={zhHans}
                    // 内部的值
                    value={this.state.value}
                    plugins={plugins}
                    onChange={(v: string) => {
                        this.setMyState({value: v})
                    }}
                    uploadImages={this.uploadImg}
                />

                {this.dialogJsx()}
            </div>
        )
    }
}

export default withRouter(ByteMd)